package com.ehsunbehravesh.mypasswords.io;

import com.ehsunbehravesh.mypasswords.Logger;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Observable;

public class FileSaver extends Observable implements Runnable {

  private File file;
  private byte[] contentOfFile;
  private int bufferSize;
  private FileOutputStream fileOutputStream;

  public FileSaver(File file, byte[] contentOfFile, int bufferSize) {
    this.file = file;
    this.contentOfFile = contentOfFile;
    this.bufferSize = bufferSize;
    if (bufferSize > contentOfFile.length) {
      bufferSize = contentOfFile.length;
    }
  }

  @Override
  protected void finalize() throws Throwable {
    if (fileOutputStream != null) {
      fileOutputStream.close();
    }
    super.finalize();
  }  
  
  public void run() {    
    int startIndex = 0;
    int endIndex = bufferSize - 1;
       
    try {
      fileOutputStream = new FileOutputStream(file);
      
      boolean endOfContent = false;
      while (!endOfContent) {
        endOfContent = endIndex == contentOfFile.length - 1;
        
        
        byte[] buffer = new byte[endIndex - startIndex + 1];
        System.arraycopy(contentOfFile, startIndex, buffer, 0, buffer.length);
        fileOutputStream.write(buffer);
        
        
        startIndex = endIndex + 1;
        endIndex = endIndex + bufferSize - 1;
        
        if (endIndex > contentOfFile.length - 1) {
          endIndex = contentOfFile.length - 1;
        }                
        
        setChanged();
        notifyObservers(new FileSaverMessage(FileSaverMessage.PROGRESS));
        Thread.sleep(1);
      }
      setChanged();
      notifyObservers(new FileSaverMessage(FileSaverMessage.FINISHED, ""));    
    } catch (Exception ex) {
      setChanged();
      notifyObservers(new FileSaverMessage(FileSaverMessage.EXCEPTION, ex.getMessage()));
      Logger.log(ex.getMessage());      
    } finally {
      if (fileOutputStream != null) {
        try {
          fileOutputStream.close();
        } catch (IOException ex) {
          Logger.log(ex.getMessage());
        }
      }
    }
  }
}
